from datetime import datetime

import pandas as pd

from client import es_client
from utils.date_utils import timestamp_to_date
from utils.geo_utils import process_location_data


async def save_single_compare_location(data_item, project_id, is_floor: bool):
    timestamp = pd.to_datetime(timestamp_to_date(data_item['timestamp']))
    bucket_time = None
    if is_floor:
        bucket_time = timestamp.floor('15min')
    else:
        bucket_time = timestamp.ceil('15min')

    # 构建存储路径（Windows 绝对路径）
    if bucket_time is not None:
        date_str = bucket_time.strftime("%Y-%m-%dT%H:%M:%S.000Z")
        # 构建存储路径（Windows 绝对路径）
        location_data = {
            'imei': data_item['device_id'],
            'project_id': project_id,
            'date_bucket': date_str,
            'location': {'lon': data_item['longitude'], 'lat': data_item['latitude']}
        }
        es = await es_client.get_es_client()
        await es.index_document(index='p_compare_location', doc=location_data)


async def save_single_compare_step(data_item, project_id):
    timestamp = pd.to_datetime(timestamp_to_date(data_item['timestamp']))
    bucket_time = timestamp.floor('H')
    # 构建存储路径（Windows 绝对路径）
    date_str = bucket_time.strftime("%Y-%m-%dT%H:%M:%S.000Z")
    # 构建存储路径（Windows 绝对路径）
    step_data = {
        'imei': data_item['device_id'],
        'project_id': project_id,
        'date_bucket': date_str,
        'step_hour': data_item['step_hour']
    }
    es = await es_client.get_es_client()
    await es.index_document(index='p_compare_step', doc=step_data)


async def save_single_compare_health(data_item, project_id, is_floor: bool):
    timestamp = pd.to_datetime(timestamp_to_date(data_item['timestamp']))
    bucket_time = None
    if is_floor:
        bucket_time = timestamp.floor('30min')
    else:
        bucket_time = timestamp.ceil('30min')
    # 构建存储路径（Windows 绝对路径）
    if bucket_time is not None:
        date_str = bucket_time.strftime("%Y-%m-%dT%H:%M:%S.000Z")
        # 构建存储路径（Windows 绝对路径）

        health_data = {
            'imei': data_item['device_id'],
            'project_id': project_id,
            'date_bucket': date_str,
            "blood_pressure_high": data_item['blood_pressure_high'],
            "blood_pressure_low": data_item['blood_pressure_low'],
            "blood_oxygen": data_item['blood_oxygen'],
            "heart_rate": data_item['heart_rate'],
            "body_temperature": 0
        }
        if data_item['body_temperature'] > '':
            health_data["bodyTemperature"] = float(data_item['body_temperature'])
        es = await es_client.get_es_client()
        await es.index_document(index='p_compare_health', doc=health_data)


async def find_same_position(date: str, project_id):
    # 1. 从ES拉取指定分桶和项目的数据
    es = await es_client.get_es_client()
    date_area = await find_before_hour_date()
    query = {
        "size": 1000,
        "query": {
            "bool": {
                "must": [
                    {"term": {"project_id": project_id}},
                    {"exists": {"field": "location"}},
                    {"range": {
                        "date_bucket": {
                            "gte": date_area['date_start'],
                            "lte": date_area['date_over']
                        }
                    }}
                ]
            }
        }
    }
    devices = await es.search_documents('p_compare_location', query=query)
    return process_location_data(devices)


async def find_before_hour_date(date: datetime = datetime.now(), hour_before: int = 2):
    time_now = pd.to_datetime(date)
    time_last_hour = time_now.floor('15min')
    time_start = time_last_hour - pd.Timedelta(hours=hour_before)
    date_start = time_start.strftime("%Y-%m-%dT%H:%M:%S.000Z")
    date_over = time_last_hour.strftime("%Y-%m-%dT%H:%M:%S.000Z")
    return {'date_start': date_start, 'date_over': date_over}